package com.lagou.edu.service.Impl;


import com.lagou.edu.dao.TokenDao;
import com.lagou.edu.pojo.LagouToken;
import com.lagou.edu.service.ClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class ClientServiceImpl implements ClientService {


    @Autowired
    private TokenDao tokenDao;



    @Override
    public String generateToken(String email, String pwd) {
        return email + pwd;
    }

    @Override
    public LagouToken saveEmailToken(String email, String token) {
        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        lagouToken.setToken(token);
        LagouToken re = tokenDao.save(lagouToken);
        return re;
    }

    @Override
    public boolean isRegistered(String email) {
        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        Example<LagouToken> example = Example.of(lagouToken);
        boolean exists = tokenDao.exists(example);
        return exists;
    }

    @Override
    public String validateUser(String email, String password) {
        String s = generateToken(email, password);
        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        lagouToken.setToken(s);
        Example<LagouToken> example = Example.of(lagouToken);
        if(tokenDao.exists(example)){
            return "error";
        }
        return "success";
    }

    @Override
    public String getEmailByToken(String token) {
        try {
            LagouToken lagouToken = new LagouToken();
            lagouToken.setToken(token);
            Example<LagouToken> example = Example.of(lagouToken);
            LagouToken lagouToken1 = tokenDao.findOne(example).get();
            if (lagouToken1 == null) {
                return "";
            }
            return lagouToken1.getEmail();
        } catch (Exception e){
            return "";
        }
    }
}
